<!-- eslint-disable no-console -->
<template>
  <CommonPage back>
    <div class="flex">
      <n-card class="min-w-200 w-25%" title="✨ 基础属性">
        <n-space vertical>
          <n-form
            :model="goodsPO" label-placement="left" :label-width="80" :disabled="updateDisabled" :style="{
              maxWidth: '640px',
            }"
          >
            <n-form-item label="商品名" path="goodsName">
              <n-input v-model:value="goodsPO.goodsName" placeholder="Input" />
            </n-form-item>
            <n-form-item label="商品简介" path="brief">
              <n-input v-model:value="goodsPO.brief" type="textarea" placeholder="Input" />
            </n-form-item>
            <n-form-item label="原价格" path="originPrice">
              <n-input-number v-model:value="goodsPO.originPrice" />
            </n-form-item>
            <n-form-item label="折后价格" path="price">
              <n-input-number v-model:value="goodsPO.price" />
            </n-form-item>
            <n-form-item label="重量" path="weight">
              <n-input v-model:value="goodsPO.weight" placeholder="weight">
                <template #password-visible-icon />
              </n-input>
            </n-form-item>
            <n-form-item label="商品图片" path="goodsPics">
              <n-upload
                v-model:file-list="goodsPO.goodsPicsVO" action="http://127.0.0.1:8878/system/file/upload/img"
                list-type="image-card" @on-finish="handleUploadFinish"
              >
                点击上传
              </n-upload>
            </n-form-item>
          </n-form>
        </n-space>
        <template #action>
          <NButton type="tertiary" @click="saveOrUpdateGoods()">
            保存
          </NButton>
        </template>
      </n-card>
      <n-card class="ml-12 w-70%" title="✨ 扩展属性">
        <template #header-extra>
          <NButton type="tertiary" @click="modalGoodsAttrValues({}, 10)">
            新增属性
          </NButton>
        </template>
        <n-data-table :bordered="false" :single-line="false" :columns="columnsAttr" :data="goodsAttrList" />
      </n-card>
    </div>
  </CommonPage>
  <!-- -----------------商品标签end------------------------ -->
  <!-- -----------------新增商品属性------------------------ -->
  <MeModal ref="$modalGoodsAttrValues">
    <n-form-item label="属性名">
      <n-input v-model:value="goodsAttrForm.attrName" :disabled="goodsAttrForm.disableEntity" />
    </n-form-item>
    <n-form-item label="可选值">
      <n-input v-model:value="goodsAttrForm.attrValueName" />
    </n-form-item>
    <n-form-item label="附加价格">
      <n-input-number v-model:value="goodsAttrForm.attrValuePrice">
        <template #suffix>
          元
        </template>
      </n-input-number>
    </n-form-item>
    <n-form-item label="商品图片" path="goodsPics">
      <n-upload
        v-model:file-list="goodsAttrForm.attrValuePicsVO" action="http://127.0.0.1:8878/system/file/upload/img"
        list-type="image-card"
      >
        点击上传
      </n-upload>
    </n-form-item>
  </MeModal>
</template>

<script setup>
import apiGlobal from '@/api'
import { MeModal } from '@/components'
import { useModal } from '@/composables'
import { NButton } from 'naive-ui'
import api from './api'

defineOptions({ name: 'GoodsModel' })
const [$modalGoodsAttrValues] = useModal()
const route = useRoute()
const goodsId = route.query.goodsId // 路由携带的参数
const goodsPO = ref({})
const goodsAttrList = ref([])
const goodsAttrForm = ref({})
const columnsAttr = [
  {
    title: '属性名',
    align: 'center',
    key: 'attrName',
    rowSpan: (rowData) => {
      if (rowData.rowSpan) {
        return rowData.rowNum
      }
      else {
        return 1
      }
    },
  },
  {
    title: '值包含',
    align: 'center',
    key: 'attrValueName',
  },
  {
    title: '附加价格',
    align: 'center',
    key: 'attrValuePrice',
  },
  {
    title: '图片',
    align: 'center',
    key: 'attrValuePics',
  },
  {
    title: '操作',
    key: 'actions',
    fixed: 'right',
    align: 'center',
    hideInExcel: true,
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'tiny',
            type: 'primary',
            secondary: true,
            onClick: () => modalGoodsAttrValues(row, 20),
          },
          {
            default: () => '新增同属性值',

            icon: () => h('i', { class: 'i-carbon:user-role text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'tiny',
            type: 'primary',
            style: 'margin-left: 12px;',
            onClick: () => modalGoodsAttrValues(row, 21),
          },
          {
            default: () => '修改',
            icon: () => h('i', { class: 'i-radix-icons:reset text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'tiny',
            type: 'warning',
            style: 'margin-left: 12px;',
            onClick: async () => {
              // await api.deleteAttr(row)
              // trans(row.goodsId)
            },
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-radix-icons:reset text-14' }),
          },
        ),
      ]
    },
  },
]
onMounted(async () => {
  if (goodsId) {
    getGoodsPOById(goodsId)
  }
  else {
    goodsPO.value = {}
    goodsPO.value.goodsPicsVO = [{
      id: 'c',
      name: '我是自带url的图片.png',
      status: 'finished',
      url: 'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg',
    }]
  }
})
async function getGoodsPOById(goodsId) {
  goodsPO.value = await apiGlobal.getGoodsPOById(goodsId)
  // 转化goodsPicsVO格式
  goodsPO.value.goodsPicsVO = goodsPO.value.goodsPics?.split(',').map(name => ({
    id: name, // 固定 id 或生成随机 id
    name,
    url: name,
    status: 'finished',
  }))
  // 转换后的数据
  const transformedData = []
  // 遍历原始数据的每个对象
  goodsPO.value.goodsAttrPOS.forEach((item) => {
    item.goodsAttrValues.forEach((goodsAttrValue) => {
      const newData = {
        goodsId: goodsPO.value.id,
        attrId: item.id,
        attrName: item.attrName,
        attrValueId: goodsAttrValue.id,
        attrValueName: goodsAttrValue.attrValueName,
        attrValuePrice: goodsAttrValue.attrValuePrice,
        attrValuePics: goodsAttrValue.attrValuePics,
      }
      // 控制合并逻辑
      if (!item.rowSpan) {
        item.rowSpan = true
        newData.rowSpan = true // 设置合并
        newData.rowNum = item.goodsAttrValues.length // 合并的行数
      }
      transformedData.push(newData)
    })
  })
  goodsAttrList.value = transformedData
}
/**
 *
 * @param {} item
 * @param {*} modalType 10 新增一级属性，20新增二级属性，21二级修改属性
 */
function modalGoodsAttrValues(item, modalType) {
  if (modalType === 10) {
    item.disableEntity = false
    item.goodsId = goodsPO.value.id
  }
  else if (modalType === 20) {
    item.disableEntity = true
    item.attrValueId = null
  }
  else {
    item.disableEntity = true
  }
  goodsAttrForm.value = item
  goodsAttrForm.value.attrValuePicsVO = item.attrValuePics?.split(',').map(name => ({
    id: name, // 固定 id 或生成随机 id
    url: name,
    status: 'finished',
  }))
  $modalGoodsAttrValues.value?.open({
    title: '新增属性',
    width: '400px',
    okText: '确定',
    cancelText: '取消',
    async onOk() {
      await api.addOrUpdateAttr(goodsAttrForm.value)
    },
    onCancel(message) {
      $message.info(message ?? '已取消')
    },
  })
}
/**
 * 保存商品-基础属性
 */
async function saveOrUpdateGoods() {
  const goodsBaseForm = goodsPO.value
  goodsBaseForm.goodsAttrPOS = []//
  goodsBaseForm.goodsPics = goodsBaseForm.goodsPicsVO?.map(item => item.name).join(',')
  await api.goodsSaveOrUpdate(goodsBaseForm)
}
// -----------------------------------------------------------------
function handleUploadFinish() {
  console.warn('handleUploadFinish')
}
</script>

<style>
.header-drawer {
  /* display: flex; */
  justify-content: center !important;
  text-align: center;
}
</style>
